$(document).ready(function(){
	
	// Load UI components
	$(function() {
		$( "input:submit").button();
		
		$( "#d1" ).dialog({
			autoOpen: false,
			modal: true,
			resizable:false,
		});
		
		$( "#d2" ).dialog({
			autoOpen: false,
			modal: true,
			resizable:false,
			width:"auto",
		});
		
		$("#d2").click(function(){
			$("#d2").dialog("close");
		});
		
		$( "#radioGroup" ).buttonset();
	});
		
	$("#back").button();
	$("#back").click(function(){
		  $("#page").toggle();
		  $("#visualization").toggle();
		  $("#d2").dialog("close");
	});
			
	// Focusing the input text box:
	$("#s").focus();

	$("#searchForm").submit(function(){
		itemSearch();
		return false;
	});
	
	$("#visualization").hide();
	
	$("#legend").click(function(event) {
		event.preventDefault();
		$("#d2").html("<div style=\"margin-top:10%\"><table><tr><td bgcolor=\"#009900\" width=20 height=20>&nbsp;</td><td style=\"color:#009900\">Positive Review</td></tr><tr><td bgcolor=\"#CC0028\" width=20 height=20>&nbsp;</td><td style=\"color:#CC0028\">Negative Review</td></tr><tr><td bgcolor=\"#0073EA\" width=20 height=20>&nbsp;</td><td style=\"color:#0073EA\">Positive Sentence</td></tr><tr><td bgcolor=\"#FF0084\" width=20 height=20>&nbsp;</td><td style=\"color:#FF0084\">Negative Sentence</td></tr></table></div>");
		$("#d2").dialog("open");
		return false;
	});
	  
	$("a.list").live("click", function(event) {
		  event.preventDefault();

		  $("#d1").html("<p>The server is capturing and analyzing user reviews from several websites.</p><img class=\"progress\" src=\"/sfe-fyp/image/spinner.gif\"/><p>The analyzing process is sophisticated, so please wait...</p>");
		  $("#d1").dialog("open");

		  $.ajax({
			  type: "GET",
			  url: $(this).attr("href"),contentType: "application/json; charset=utf-8",
			  dataType: "json",
			  data: {},
			  success: function(r){
				  $("#page").toggle();
				  $("#visualization").toggle();
				  $("#d1").dialog("close");
				  
				  $("p.group2").text("");
				  $("p.group3").text("");
				  $("#subtitle").text("");
				  
				  var sentwords = r.responseData.group2;
				  var abstracts = r.responseData.group3;
	
				  var til = r.responseData.title;
				  var idx = til.indexOf(":");
				  if(idx!=-1){
					  var title = til.substring(0,idx);
					  var subtitle = til.substring(idx);
					  $("#title").text(title);
					  $("#subtitle").text(subtitle);
				  }
				  else{
					  $("#title").text(til);
					  $("#subtitle").text("");
				  }
			  
				  $("#rating").text(r.responseData.rating);
				  
				  var mapOfAbstractOfReview={};
				  if(r.responseData.fav!=null){
					  $("#po1").text(r.responseData.fav.abst);
					  $("#po1").click(function() {
							$("#d2").text(r.responseData.fav.text);
							$("#d2").dialog("open");
							return false;
					  });
				  }
				  if(r.responseData.cri!=null){
					  $("#po2").text(r.responseData.cri.abst);
					  $("#po2").click(function() {
							$("#d2").text(r.responseData.cri.text);
							$("#d2").dialog("open");
							return false;
					  });
				  }
				  
				  var goodColors = ["#00CC00","#00FF00","#66FF66"];
				  var badColors = ["#FF335B","#FF99AD","#FFCBD6"];
				  var gdIndex=0;
				  var bdIndex=0;
				  
				  for(var i=0;i<abstracts.length;i++){
					  var abstr = abstracts[i];
					  var str = "#po"+(i+3);
					  $(str).text(abstr.abst);
					  if(abstr.score>3){
						  $(str).css("color",goodColors[gdIndex++]);						  
					  } else{
						  $(str).css("color",badColors[bdIndex++]);
					  }

					  mapOfAbstractOfReview[$(str).attr("id")] = abstr.text;
					  $(str).click(function() {
							$("#d2").text(mapOfAbstractOfReview[$(this).attr("id")]);
							$("#d2").dialog("open");
							return false;
					  });
				  }

				  var mapOfSentiWordsToSentence={};
				  var j = 0;
				  for(var i=0;i<sentwords.length;i++){
					  var list = sentwords[i].tagWord;
					  var color = "gray";
					  if(sentwords[i].score>0)
						  color = "#0073EA";
					  else if(sentwords[i].score<0)
						  color = "#FF0084";
					  
					  for(var k=0;k<list.length;k++){
						  var str = "p.group2:eq("+j+")";
						  $(str).text(list[k]);
						  $(str).css("color",color);
	
						  mapOfSentiWordsToSentence[$(str).attr("id")] = sentwords[i].sentence;
						  $(str).click(function() {
								$("#d2").html(mapOfSentiWordsToSentence[$(this).attr("id")]);
								$("#d2").dialog("open");
								return false;
						  });
						  
						  j++;
					  }
				  }

			  },
			  error:function (xhr, textStatus, errorThrown) {
				  alert(xhr.responseText);
			  }
		});
		  return false;
		});	
	
	function itemSearch(){
				
		var query = $("#s").val();
		var category= $("input:radio[name=domain]:checked").val();
				
		// URL of server
		var apiURL = "http://localhost:8080/sfe-fyp/search/json";
		var resultsDiv = $("#resultsDiv");
		
		$.getJSON(apiURL,{query:query,category:category},function(r){
			
			var results = r.responseData;
			$("#logo").css("margin-top","0%");
			resultsDiv.empty();
			
			if(results.length){
				
				// If results are not empty, add them to the #resultsDiv:				
				var pageContainer = $("<div>",{className:"pageContainer"});
				
				for(var i=0;i<results.length;i++){
					// Add a new result
					pageContainer.append(new result(results[i],r.category) + "");
				}
				
				pageContainer.append("<div class=\"clear\"></div>")
							 .hide().appendTo(resultsDiv)
							 .fadeIn("slow");
				
			}
			else {
				// No results were found.
				resultsDiv.empty();
				var pageContainer = $("<div>",{className:"pageContainer"});
				pageContainer.append("<h3 class=\"notFound\">No Results Were Found!</h3>");
				pageContainer.append("<div class=\"clear\"></div>")
				 .hide().appendTo(resultsDiv)
				 .fadeIn();
			}
		});
	}
	
	function result(r,cat){
		//The markup is generated by the .toString() method.
		var arr = [
			"<div class=\"result\">",
			"<h3><a class=\"list\" href=\"http://localhost:8080/sfe-fyp/search/review?item=",r.title,"&amazonUrl=",r.amazonReviewURL,"&asin=",r.amazonASIN,"&category=",cat,"\">",r.title,"</a></h3>",
			"<p\">By <b>",r.authors.length!=0?r.authors:"Unknown","</b>,&nbsp;Published by <b>",r.manufacturer?r.manufacturer:"Unknown","</b></p>",
			"</div>"
		];
		
		this.toString = function(){
			return arr.join("");
		};

	}	
	
});
